<template>
    <el-dialog :visible.sync="visible" title="日志查看" @close="onClose">
        <div style="text-align: right; margin-bottom: 10px;">
            <el-button type="text" @click="onClose">停止接受日志</el-button>
        </div>
        <el-input ref="logInput" type="textarea" v-model="logValue" readonly rows="20"/>
    </el-dialog>
</template>

<script>
    export default {
        name: "log_dialog",
        data(){
            return {
                ws: null,
                visible: false,
                logValue: "",
                extra: null
            }
        },
        watch:{
            "extra.text": function (nv) {
                this.addLog(nv)
                // console.log(arguments)
            }
            // extra:{
            //     handler(){
            //         console.log()
            //     },
            //     deep: true
            // }
        },
        methods:{
            onClose() {
                try {
                    this.ws.close()
                } finally {
                    this.ws = null
                }
                this.extra = null
            },
            addLog(val) {
                if (!this.logValue) {
                    this.logValue = val
                } else {
                    this.logValue = this.logValue + "\n" + val
                }
                this.$nextTick(_ => {
                    var ele = this.$refs.logInput.$el.querySelector("textarea")
                    if (ele.scrollHeight > ele.clientHeight) {
                        //设置滚动条到最底部
                        ele.scrollTop = ele.scrollHeight;
                    }
                })
            },
            show(url, extra){
                this.ws = null
                this.logValue = ""
                if(url){
                    this.ws = new WebSocket(url)
                    this.ws.onmessage = (msg) => {
                        var d = JSON.parse(msg.data);
                        this.addLog(d.data)
                        console.log(msg)
                    }
                }
                this.extra = extra
                this.visible = true
            }
        }
    }
</script>

<style scoped>

</style>
